package com.automannn.atm_back.modules.codeGenerator.core.service;

import com.automannn.atm_back.modules.codeGenerator.core.pojo.GlobalConfig;
import com.automannn.atm_back.modules.codeGenerator.core.pojo.TableInfo;
import com.automannn.atm_back.modules.codeGenerator.core.pojo.Template;
import com.automannn.atm_back.modules.codeGenerator.core.util.*;
import org.springframework.stereotype.Component;

import java.util.Collection;
import java.util.HashMap;
import java.util.Map;

/**
 * @author chenkh
 * @time 2020/7/6 13:46
 */
@Component("freeMarkerCodeService")
public class FreeMarkerCodeService implements CodeService {

    @Override
    public String generate(Template template, TableInfo tableInfo, Collection<GlobalConfig> globalConfigs) {
        //1.获取默认参数(包括java工具方法)
        Map<String, Object> param = getJavaParam();
        param.put("tableInfo",tableInfo);
        //2.设置模型路径和导包列表
        setModulePathAndImportList(param, tableInfo);
        //3.处理模板,注入全局变量
        TemplateUtils.addGlobalConfig(template, globalConfigs);
        //4.调用工具进行生成
        return FreemarkerUtils.generate(template.getCode(), param).trim();
    }

    private void setModulePathAndImportList(Map<String, Object> param, TableInfo tableInfo) {
        param.put("modulePath","com.automannn.codeTest");
        param.put("importList","com.automannn.test.*");
    }

    private Map<String, Object> getJavaParam() {
        Map<String, Object> param = new HashMap<>(20);
        // 作者
        param.put("author", "automannn");
        //工具类
        param.put("tool", GlobalTool.getInstance());
        param.put("time", TimeUtils.getInstance());
        // 项目路径
        param.put("projectPath", "com.automannn.codeTest");
        return param;
    }
}
